package MyArrysList;

import java.util.Arrays;

public class MyArrysList implements IOS{

    public int[]elem;
    public int UseSize;
    public  MyArrysList(){
        this.elem=new int[10];
    }

    @Override
    public void add(int data) {
        if (this.isFull()) {
            this.elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        this.elem[UseSize]=data;
        this.UseSize++;
    }

    @Override
    public void add(int pos, int data) {
    try {
        this.checkPosInAdd(pos);
    }catch (PosNoyLedalException e){
        e.printStackTrace();
    }
    if(isFull()){
        this.elem=Arrays.copyOf(elem,2*elem.length);
    }
        for (int i =UseSize; i >pos ; i--) {
            this.elem[i]=this.elem[i-1];

        }
        this.elem[pos]=data;
        this.UseSize++;

    }
    private void checkPosInAdd(int pos) throws PosNoyLedalException{
        if (pos < 0 || pos > UseSize) {
            throw new PosNoyLedalException("pos位置不合法");

        }
    }

    @Override
    public boolean containss(int toFind) {
        for (int i = 0; i < UseSize; i++) {
            if (this.elem[i] == toFind) {
                    return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < UseSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }

        }
        System.out.println("未能找到" + toFind);
        return -1;
    }
 private void checkPosInGetAndSet (int pos) throws PosNoyLedalException {
    if(pos<0||pos>this.UseSize-1) {
        throw new ClassCastException("Pos位置不合法");
    }
 }

    @Override
    public int get(int pos) {
        try {
            checkPosInGetAndSet(pos);
        } catch (PosNoyLedalException e) {
            e.printStackTrace();
        }
        return this.elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        try {
            checkPosInGetAndSet(pos);
        } catch (PosNoyLedalException e) {
            e.printStackTrace();
        }
        this.elem[pos]=value;
    }

    @Override
    public void remove(int toRmove) {
        int i=this.indexOf(toRmove);
        if(i==-1) {
            System.out.println("没有要删除的数字");
        }else {
            for(int j=i;i<UseSize;i++){
                this.elem[j]=this.elem[j+1];
            }
            UseSize--;
        }
    }

    @Override
    public int size() {
        return this.UseSize;
    }

    @Override
    public void clear() {
            this.UseSize=0;
    }

    @Override
    public void display() {
        for(int i=0;i<this.UseSize;i++){
            System.out.println(this.elem[i]+"  ");
        }
    }

    @Override
    public boolean isFull() {
        return this.UseSize==this.elem.length;
        }
    }

